package com.jule.chat.network.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by xujian on 2017/5/16 0016.
 */
public abstract class Request implements Cloneable, Runnable {
    private final static Logger logger = LoggerFactory.getLogger(Request.class);

    protected ChannelHandlerContext ctx;
    protected int functionId;

    public Request(int functionId) {
        this.functionId = functionId;
    }

    public void setCtx(ChannelHandlerContext ctx) {
        this.ctx = ctx;
    }

    public boolean readPayLoad(ByteBuf buf) {
        try {
            readPayLoadImpl(buf);
        } catch (Exception e) {
            logger.error("io error", e);
            return false;
        }
        return true;
    }

    public abstract void readPayLoadImpl(ByteBuf buf) throws Exception;

    @Override
    public void run() {
        try {
            processImpl();
        } catch (Exception e) {
            logger.error("业务处理异常", e);
        }
    }

    public abstract void processImpl() throws Exception;

    public Request clone() {
        try {
            return (Request) super.clone();
        } catch (CloneNotSupportedException e) {
            return null;
        }
    }
}
